import uuid

from fastapi import APIRouter, Request

from pyJianYingDraft import Export_resolution, Export_framerate
from .base import RouterMeta
from src.constants.resultcode import ResultCode
from src.utils.response import ApiResponse
from src.utils.logger import get_logger
from src.schemas.common import RenderTaskRequest, RenderTaskStatusRequest, RenderTaskListRequest
from ..service.render_task import TaskStatusManager
from ..service.save_draft import query_script
from ..service.video_service import process_video_task
import json
logger = get_logger("capcut")
router = APIRouter()
status_manager = TaskStatusManager()


@router.post("/submit_task", name="云渲染—提交生成任务")
async def submit_task(request: Request, render_task_request: RenderTaskRequest):
    draft_id = render_task_request.draft_id
    task_id = str(uuid.uuid4())

    try:
        # 根据draft_id读取缓存判断是否包含时间线
        script = query_script(draft_id, force_update=False)
        script_json = script.dumps()
        logger.debug(f"获取草稿脚本数据: draft_id={draft_id}, script_json={script_json[:100]}...")

        # 解析JSON数据
        try:
            script_dict = json.loads(script_json)
        except json.JSONDecodeError as e:
            error_msg = f"脚本数据格式错误: {str(e)}"
            logger.error(f"云渲染—提交生成任务失败: {error_msg}", exc_info=True)
            return ApiResponse.error(
                result_code=ResultCode.ERROR,
                message=error_msg
            )

        # 提取tracks字段，默认为空列表
        tracks = script_dict.get('tracks', [])
        logger.debug(f"提取tracks字段: draft_id={draft_id}, tracks_count={len(tracks)}")

        # 判断tracks是否为空
        if not isinstance(tracks, list) or len(tracks) == 0:
            error_msg = "时间线为空，无法提交渲染任务"
            logger.warning(f"云渲染—提交生成任务失败: {error_msg}, draft_id={draft_id}")
            return ApiResponse.error(
                result_code=ResultCode.ERROR,
                message=error_msg
            )

        # 初始化任务状态
        status_manager.init_task_status(task_id, draft_id )

        # 使用Huey提交任务
        process_video_task(task_id, draft_id, render_task_request.resolution, render_task_request.framerate)

        return ApiResponse.success(
            data={
                'task_id': task_id,
                'status': TaskStatusManager.STATUS_QUEUED,
                'message': '任务已成功提交'
            }
        )

    except Exception as e:
        logger.error(f"云渲染—提交生成任务失败: {str(e)}", exc_info=True)
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message=f"提交生成任务失败: {str(e)}"
        )

@router.post("/task_status",name="云渲染—查询任务状态")
async def task_status(request: Request, render_task_status_request: RenderTaskStatusRequest):
    """查询任务状态API"""

    try:
        status_data = status_manager.get_task_status(render_task_status_request.task_id)

        return ApiResponse.success(
            data=status_data
        )
    except Exception as e:
        logger.error(f"云渲染—查询任务状态失败: {str(e)}", exc_info=True)
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message=f"查询任务状态失败: {str(e)}"
        )

@router.post("/task_list",name="云渲染—任务列表")
async def task_status(request: Request, render_task_list_request: RenderTaskListRequest):

    try:
        task_list = status_manager.get_draft_tasks_all(render_task_list_request.draft_id)

        return ApiResponse.success(
            data=task_list
        )
    except Exception as e:
        logger.error(f"云渲染—查询任务列表失败: {str(e)}", exc_info=True)
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message=f"查询任务列表失败: {str(e)}"
        )


meta = RouterMeta(
    router=router,
    prefix="/render",
    tags=["云渲染"]
)